package edu.pitt.dbmi.odie.gapp.gwt.server.util.gdata;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;

import edu.pitt.dbmi.odie.gapp.gwt.server.user.ODIE_ServerSideLoginInfo;

public class ODIE_DocsServiceFetcher {
	
	/**
	 * Field logger.
	 */
	private static final Logger logger = Logger.getLogger(ODIE_DocsServiceFetcher.class);

	private static final String CONST_DOCS_SERVICE = "docsService" ;
	
	public static ODIE_GDataDocsService fetchOrCreateDocsService(ServletConfig config, ODIE_ServerSideLoginInfo serverSideLoginInfo) {
		ODIE_GDataDocsService docsService = fetchDocsService(config) ;
		if (docsService == null) {
			docsService = new ODIE_GDataDocsService(serverSideLoginInfo) ;
			cacheDocsService(config, docsService) ;	
		}
		else {
			logger.debug("fetched existing docsService") ;
		}
		return docsService ;
	}
	
	public static void releaseDocsService(ServletConfig config) {
		try {
			ServletContext context = config.getServletContext() ;
			context.removeAttribute(CONST_DOCS_SERVICE) ;
		}
		catch (NullPointerException x) {
			x.printStackTrace();
		}
	}
	
	public static ODIE_GDataDocsService fetchDocsService(ServletConfig config) {
		ODIE_GDataDocsService docsService = null ;
		try {
			ServletContext context = config.getServletContext() ;
			docsService = (ODIE_GDataDocsService) context.getAttribute("docsService") ;
		}
		catch (NullPointerException x) {
			x.printStackTrace();
		}
		return docsService ;
	}
	
	private static void cacheDocsService(ServletConfig config, ODIE_GDataDocsService docsService) {
		try {
			config.getServletContext().setAttribute("docsService", docsService) ;
			logger.debug("cached new docsService") ;
		}
		catch (NullPointerException x) {
			logger.warn("Failed with null servletContext.") ;
		}
	}
	

}
